package com.computergames.server.protocol;

import com.computergames.server.message.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;

@Slf4j
public class MessageCodec extends ByteToMessageCodec<Message> {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Message message, ByteBuf byteBuf) throws Exception {
        //1. 4字节的魔数
        byteBuf.writeBytes(new byte[]{'c','g','c','p'});
        //2. 1字节的协议版本
        byteBuf.writeByte(1);
        //3. 1字节的序列化方式 jdk 0， json 1
        byteBuf.writeByte(0);
        //4. 1字节的指令类型
        byteBuf.writeByte(message.getMessageType());
        //5. 4字节的请求序号，提供异步能力
        byteBuf.writeInt(message.getSequenceId());
        // 无意义，对齐填充凑齐16字节
        byteBuf.writeByte(0xff);
        //6. 获取内容的字节数组
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(message);
        byte[] bytes = bos.toByteArray();
        //7. 长度
        byteBuf.writeInt(bytes.length);
        //8. 写入内容
        byteBuf.writeBytes(bytes);
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        int magicNum = byteBuf.readInt();
        if (magicNum != 0x63676370) {
            throw new RuntimeException("不识别的协议包");
        }
        byte version = byteBuf.readByte();
        byte serializerType = byteBuf.readByte();
        byte messageType = byteBuf.readByte();
        int sequenceId = byteBuf.readInt();
        byteBuf.readByte();
        int length = byteBuf.readInt();
        byte[] bytes = new byte[length];
        byteBuf.readBytes(bytes,0, length);

        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
        Message message = (Message) ois.readObject();

        log.info("{},{},{},{},{},{}", magicNum, version, serializerType, messageType, sequenceId, length);
        log.info("{}", message);
        list.add(message);
    }
}
